// 在数组的两边找到两个数相加会等于x
// 转换思路，其实就是要求一段区间使得和为sum - x;
#include <vector>
using namespace std;
// 这里的妙处就是数据都是正的
// 所以就可以转换思路用滑动窗口来做
// 但是一定要注意刚好为0的情况，删去整个数组即可
class Solution
{
public:
    int minOperations(vector<int> &nums, int x)
    {
        int n = nums.size();
        int left = 0, right = 0;
        // 可能会有很多种解，需要保存的是最优解
        int final_left = 0, final_right = 0, ans = 0;
        int target = -x;
        for (int i = 0; i < n; ++i)
            target += nums[i];
        // cout << target << endl;
        if (target < 0)
            return -1;
        else if (target == 0)
        {
            for (int i = 0; i < n; ++i)
                nums[i] = 0;
            return n;
        }
        int sum = 0;
        while (right < n)
        {
            sum += nums[right++];
            while (sum > target)
                sum -= nums[left++];
            if (sum == target && right - left > ans)
            {
                // cout << left << ' ' << right << endl;
                final_left = left, final_right = right;
                ans = right - left;
            }
        }
        if (!final_right)
            return -1;
        else
        {
            for (int i = 0; i < final_left; ++i)
                nums[i] = 0;
            for (int i = final_right; i < n; ++i)
                nums[i] = 0;
            return n - ans;
        }
    }
};